package com.xxgc.eow.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xxgc.eow.client.WechatClient;
import com.xxgc.eow.client.response.WechatLoginResponse;
import com.xxgc.eow.client.response.WechatPhoneInfoResponse;
import com.xxgc.eow.client.response.WechatTokenResponse;
import com.xxgc.eow.controller.dto.UserLoginDTO;
import com.xxgc.eow.entity.SystemConfig;
import com.xxgc.eow.entity.Users;
import com.xxgc.eow.result.Result;
import com.xxgc.eow.service.ISystemConfigService;
import com.xxgc.eow.service.IUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;


/**
 * @program: ExhibitionOfWorks
 * @description: 用户注册登录相关
 * @author: Mr.Abel SJY
 * @Email thanksjava@qq.com
 * @create: 2023-05-07 16:56
 **/
@Tag(name = "用户注册登录相关")
@RestController
@RequestMapping("/auth")
public class UserLoginController {

    @Autowired
    private WechatClient wechatClient;
    @Autowired
    private ISystemConfigService iSystemConfigService;
    @Autowired
    private IUsersService ius;


    /***
     * 微信小程序登录
     * @param ul 请求参数
     * @param response 响应体
     * @return
     */
    @ApiOperationSupport(author = "石老师 thanksjava@qq.com")
    @Operation(summary = "微信小程序用户登录", description = "通过微信小程序api调用")
    @Parameters({
            @Parameter(name = "code",description = "可通过wx.login获取",required = true,in= ParameterIn.QUERY),
            @Parameter(name = "nickName",description = "昵称（新用户用此昵称注册，已注册用户此字段无效）",required = true,in= ParameterIn.QUERY),
            @Parameter(name = "avatarUrl",description = "头像（新用户用此昵称注册，已注册用户此字段无效）",required = true,in= ParameterIn.QUERY)
    })
    @SaIgnore
    @PostMapping("/login")
    public Result<Users> userLogin(@RequestBody UserLoginDTO ul,
                                   HttpServletResponse response){
        //获取appId
        String appId = iSystemConfigService.getOne(new QueryWrapper<SystemConfig>().eq("con_key", "appId")).getConValue();
        //获取appSecret
        String appSecret = iSystemConfigService.getOne(new QueryWrapper<SystemConfig>().eq("con_key", "appSecret")).getConValue();
        //调用接口
        WechatLoginResponse ac = wechatClient.wechatLogin(appId, appSecret, ul.getCode(), "authorization_code");
        //登录成功
        if(ac.getErrcode() == 0){
            //判断数据库有没有,没有就注册
            Users users = ius.getOne(new QueryWrapper<Users>().eq("openid", ac.getOpenid()));
            if(users == null){
                users = new Users();
                users.setOpenid(ac.getOpenid());
                users.setNickname(ul.getNickName());
                users.setProfilePhoto(ul.getAvatarUrl());
                int insert = ius.getBaseMapper().insert(users);
                StpUtil.login(insert);
            }else{
                //存入用户id
                StpUtil.login(users.getId());
            }
            //携带token返回
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            response.setHeader("token",tokenInfo.getTokenValue());
            return Result.ok(users);
        }else{
            return Result.error("登录失败");
        }

    }


    @ApiOperationSupport(author = "石老师 thanksjava@qq.com")
    @Operation(summary = "获取用户手机号（登录后）", description = "获取用户手机号返回并保存到用户账号中（目前该接口针对非个人开发者）")
    @Parameters({
            @Parameter(name = "code",description = "动态令牌有效期为5分钟",required = true,in = ParameterIn.PATH),
            @Parameter(name = "Authorization",description = "请求的token",required = true,in = ParameterIn.HEADER)
    })
    @SaCheckLogin
    @PostMapping("/phoneNumber/{code}")
    public Result<WechatPhoneInfoResponse> getUserPhoneNumber(@PathVariable("code") String code){
        //获取appId
        String appId = iSystemConfigService.getOne(new QueryWrapper<SystemConfig>().eq("con_key", "appId")).getConValue();
        //获取appSecret
        String appSecret = iSystemConfigService.getOne(new QueryWrapper<SystemConfig>().eq("con_key", "appSecret")).getConValue();
        //拿到token
        WechatTokenResponse wtr = wechatClient.wechatTokenResponse("client_credential", appId, appSecret);

        WechatPhoneInfoResponse wpir = wechatClient.wechatGetuserphonenumber(wtr.getAccess_token(), code);
        //可以注册到账户里面去
        System.out.println("wpir = " + wpir);
        return Result.ok(wpir);
    }

}
